import React, { useEffect, useReducer } from 'react';
import { LockOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import LineChartCard from '@/components/report/lineChartCard';
import EmplDataChart from '@/components/report/emplDataChart';
import CompClieAnalysis from '@/components/report/compClieAnalysis';
import IndiClieAnalysis from '@/components/report/indiClieAnalysis';
import EmplAnalysis from '@/components/report/emplAnalysis';
import Dept2Analysis from '@/components/report/dept2Analysis';
import Dept1Analysis from '@/components/report/dept1Analysis';
import { getChartCardAll } from '@/services/report';
import { changePassword } from '@/services/user';
import {
  getFirstDayOfMonth,
  getFirstDayOfYear,
  getFirstDayOfSeason,
  format,
} from '@/utils/datetime';
import {
  Row,
  Col,
  Spin,
  Alert,
  Card,
  Tabs,
  DatePicker,
  Radio,
  Dropdown,
  Menu,
  Button,
  Divider,
  message,
  Modal,
} from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { DownOutlined } from '@ant-design/icons';
import moment from 'moment';
import _ from 'lodash';
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
type StateField = {
  currdate?: string;
  sdate?: string;
  edate?: string;
  cyno?: string;
  timeLevel?: string;
  emplLevel?: string;
  emplID?: number;
  tabKey?: string;
  hasComp?: boolean;
  hasIndi?: boolean;
  hasRmb?: boolean;
  chartCards?: API.ChartCardData[];
  loading?: boolean;
  isInitPwd?: boolean;
};
const Welcome: React.FC = () => {
  const { user, sys, appNo } = useModel('@@initialState', (ret) => ({
    user: ret.initialState?.user,
    sys: ret.initialState?.sys,
    appNo: ret.initialState?.appNo,
  }));
  const [state, dispatch] = useReducer(
    (prevState: StateField, newState: StateField) => {
      return { ...prevState, ...newState };
    },
    {
      currdate: undefined,
      sdate: undefined,
      edate: undefined,
      cyno: '1',
      timeLevel: undefined,
      emplLevel: undefined,
      emplID: undefined,
      tabKey: '1',
      hasComp: false,
      hasIndi: false,
      hasRmb: false,
      chartCards: [],
      loading: false,
      isInitPwd: user?.isInitPwd,
    },
  );
  useEffect(() => {
    if (user === undefined || sys === undefined) {
      return;
    }
    const emplLevel = user.homeLevel;
    let currdate = sys.edwDate!;
    if (appNo == 'tj' || appNo == 'nj') {
      currdate = sys.odsDate!;
    }
    const d = new Date(currdate);
    const sdate = format(getFirstDayOfMonth(d), 'yyyy-MM-dd');
    let emplID = user.userID;
    let cyno = '1';
    let hasComp = false;
    let hasIndi = false;
    let hasRmb = false;
    let tabKey = '1';
    if (user.homePermTypes!.includes('V')) {
      hasComp = true;
      hasRmb = false;
      cyno = '3';
      tabKey = '1';
    }
    if (user.homePermTypes!.includes('O')) {
      hasIndi = true;
      hasRmb = true;
      cyno = '1';
      tabKey = '3';
    }
    if (user.homePermTypes!.includes('N')) {
      hasComp = true;
      hasRmb = true;
      cyno = '1';
      tabKey = '1';
    }
    if (emplLevel === 'dept1') {
      emplID = user.pOrgID;
    } else if (emplLevel === 'dept2') {
      emplID = user.orgID;
    }
    dispatch({
      currdate,
      sdate,
      edate: state.currdate!,
      cyno,
      timeLevel: 'month',
      emplLevel,
      emplID,
      tabKey,
      hasComp,
      hasIndi,
      hasRmb,
    });
  }, [appNo, state.currdate, sys, user]);
  useEffect(() => {
    if (state.timeLevel === undefined) {
      return;
    }
    dispatch({ loading: true });
    getChartCardAll(state.cyno!, state.timeLevel!)
      .then(function (data) {
        dispatch({ chartCards: data, loading: false });
      })
      .catch(function (ex) {
        dispatch({ loading: false });
        console.error('获取首页卡片数据出错', ex);
      });
  }, [state.cyno, state.timeLevel]);
  if (
    state.sdate === undefined ||
    state.edate === undefined ||
    _.isEmpty(state.chartCards) ||
    state.loading
  ) {
    return (
      <div>
        <Spin tip="加载中...">
          <Alert message="首页加载中" description="正在加载首页的数据，请稍后" type="info" />
        </Spin>
      </div>
    );
  }
  const handleTimeLevelChange = (timeLevel: string) => {
    let sdate = state.currdate!;
    const d = new Date(sdate);
    if (timeLevel === 'year') {
      sdate = format(getFirstDayOfYear(d), 'yyyy-MM-dd');
    } else if (timeLevel === 'month') {
      sdate = format(getFirstDayOfMonth(d), 'yyyy-MM-dd');
    } else if (timeLevel === 'quarter') {
      sdate = format(getFirstDayOfSeason(d), 'yyyy-MM-dd');
    }
    dispatch({ sdate, edate: state.currdate!, timeLevel });
  };
  const span = 24 / state.chartCards!.length;
  const cols = state.chartCards!.map((cc, i) => (
    <Col key={i as React.Key} span={span} style={{ paddingLeft: i === 0 ? 0 : 10 }}>
      <LineChartCard
        lineDatas={cc.lineDatas}
        chainData={cc.chainData}
        loading={state.loading!}
        cyno={state.cyno!}
        timeLevel={state.timeLevel!}
        title={cc.title}
      />
    </Col>
  ));
  let cynoName = '本外币';
  if (state.cyno === '2') {
    cynoName = '人民币';
  } else if (state.cyno === '3') {
    cynoName = '外币';
  }
  const cynoItems = (
    <Menu onClick={(e) => dispatch({ cyno: e.key })}>
      {state.hasRmb ? <Menu.Item key="1">本外币</Menu.Item> : null}
      {state.hasRmb ? <Menu.Item key="2">人民币</Menu.Item> : null}
      <Menu.Item key="3">外币</Menu.Item>
    </Menu>
  );
  const tabsExtra = (
    <div>
      <Dropdown key="cyno" overlay={cynoItems}>
        <Button>
          {`币种:${cynoName}`}
          <DownOutlined />
        </Button>
      </Dropdown>
      <Divider type="vertical" />
      <Radio.Group
        value={state.timeLevel}
        style={{ marginTop: 16 }}
        onChange={(e) => handleTimeLevelChange(e.target.value)}
      >
        <Radio.Button value="day">日</Radio.Button>
        <Radio.Button value="month">月</Radio.Button>
        <Radio.Button value="quarter">季</Radio.Button>
        {state.emplLevel === 'all' && state.hasComp && state.hasIndi ? (
          <Radio.Button value="year">年</Radio.Button>
        ) : null}
      </Radio.Group>
      <Divider type="vertical" />
      <RangePicker
        value={[moment(state.sdate), moment(state.edate)]}
        onChange={(vals) => {
          if (_.isEmpty(vals) || _.isEmpty(vals![0]) || _.isEmpty(vals![1])) {
            return;
          }
          const sdate = vals![0]!.format('YYYY-MM-DD');
          const edate = vals![1]!.format('YYYY-MM-DD');
          dispatch({ sdate, edate });
        }}
        style={{ width: 216 }}
      />
    </div>
  );
  const paramVals = {
    sdate: state.sdate!,
    edate: state.edate!,
    cyno: state.cyno!,
    timeLevel: state.timeLevel!,
    emplLevel: state.emplLevel!,
    emplID: state.emplID!,
  };

  return (
    <>
      <Row style={{ marginBottom: 10 }} key="chartCard">
        {cols}
      </Row>
      <Card loading={state.loading} bordered={false} bodyStyle={{ padding: 0 }}>
        <Tabs
          tabBarExtraContent={tabsExtra}
          size="large"
          activeKey={state.tabKey}
          tabBarStyle={{ marginBottom: 24 }}
          onChange={(tabKey) => dispatch({ tabKey })}
        >
          {state.hasComp ? (
            <TabPane tab="对公存款" key="1">
              {state.tabKey === '1' ? (
                <>
                  <EmplDataChart
                    key="empl_dgck"
                    colName="ACBL_DGCK"
                    {...paramVals}
                    groupCalc="acbl"
                    vertical={false}
                  />
                  <Tabs size="small" tabBarStyle={{ marginBottom: 12 }}>
                    {state.emplLevel === 'all' ? (
                      <TabPane tab="管辖部门" key="1">
                        <Dept1Analysis colName="ACBL_DGCK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel === 'dept1' ? (
                      <TabPane tab="部门" key="2">
                        <Dept2Analysis colName="ACBL_DGCK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel !== 'user' ? (
                      <TabPane tab="员工" key="3">
                        <EmplAnalysis colName="ACBL_DGCK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    <TabPane tab="客户" key="4">
                      <CompClieAnalysis colName="ACBL_DGCK" {...paramVals} groupCalc="acbl" />
                    </TabPane>
                  </Tabs>
                </>
              ) : null}
            </TabPane>
          ) : null}
          {state.hasComp ? (
            <TabPane tab="对公贷款" key="2">
              {state.tabKey === '2' ? (
                <>
                  <EmplDataChart
                    key="empl_dgdk"
                    colName="ACBL_DGDK"
                    {...paramVals}
                    groupCalc="acbl"
                    vertical={false}
                  />
                  <Tabs size="small" tabBarStyle={{ marginBottom: 12 }}>
                    {state.emplLevel === 'all' ? (
                      <TabPane tab="管辖部门" key="1">
                        <Dept1Analysis colName="ACBL_DGDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel === 'dept1' ? (
                      <TabPane tab="部门" key="2">
                        <Dept2Analysis colName="ACBL_DGDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel !== 'user' ? (
                      <TabPane tab="员工" key="3">
                        <EmplAnalysis colName="ACBL_DGDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    <TabPane tab="客户" key="4">
                      <CompClieAnalysis colName="ACBL_DGDK" {...paramVals} groupCalc="acbl" />
                    </TabPane>
                  </Tabs>
                </>
              ) : null}
            </TabPane>
          ) : null}
          {state.hasIndi ? (
            <TabPane tab="储蓄存款" key="3">
              {state.tabKey === '3' ? (
                <>
                  <EmplDataChart
                    key="empl_lscx"
                    colName="ACBL_CX"
                    {...paramVals}
                    groupCalc="acbl"
                    vertical={false}
                  />
                  <Tabs size="small" tabBarStyle={{ marginBottom: 12 }}>
                    {state.emplLevel === 'all' ? (
                      <TabPane tab="管辖部门" key="1">
                        <Dept1Analysis colName="ACBL_CX" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel === 'dept1' ? (
                      <TabPane tab="部门" key="2">
                        <Dept2Analysis colName="ACBL_CX" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel !== 'user' ? (
                      <TabPane tab="员工" key="3">
                        <EmplAnalysis colName="ACBL_CX" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    <TabPane tab="客户" key="4">
                      <IndiClieAnalysis colName="ACBL_CX" {...paramVals} groupCalc="acbl" />
                    </TabPane>
                  </Tabs>
                </>
              ) : null}
            </TabPane>
          ) : null}
          {state.hasIndi ? (
            <TabPane tab="个人贷款" key="4">
              {state.tabKey === '4' ? (
                <>
                  <EmplDataChart
                    key="empl_lsgd"
                    colName="ACBL_GRDK"
                    {...paramVals}
                    groupCalc="acbl"
                    vertical={false}
                  />
                  <Tabs size="small" tabBarStyle={{ marginBottom: 12 }}>
                    {state.emplLevel === 'all' ? (
                      <TabPane tab="管辖部门" key="1">
                        <Dept1Analysis colName="ACBL_GRDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel === 'dept1' ? (
                      <TabPane tab="部门" key="2">
                        <Dept2Analysis colName="ACBL_GRDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    {state.emplLevel !== 'user' ? (
                      <TabPane tab="员工" key="3">
                        <EmplAnalysis colName="ACBL_GRDK" {...paramVals} groupCalc="acbl" />
                      </TabPane>
                    ) : null}
                    <TabPane tab="客户" key="4">
                      <IndiClieAnalysis colName="ACBL_GRDK" {...paramVals} groupCalc="acbl" />
                    </TabPane>
                  </Tabs>
                </>
              ) : null}
            </TabPane>
          ) : null}
        </Tabs>
      </Card>
      <Modal
        visible={state.isInitPwd}
        maskClosable={false}
        closable={false}
        footer={null}
        title="您的密码为初始密码，请修改"
      >
        <div style={{ marginTop: 30, marginLeft: 50, marginBottom: 50 }}>
          <Card style={{ width: 400 }}>
            <ProForm
              onFinish={async (values) => {
                if (values.newPassword !== values.okNewPassword) {
                  message.error('新密码和确认密码不一致！');
                  return;
                }
                await changePassword('00000000', values.newPassword);
                message.success('密码修改成功');
                dispatch({ isInitPwd: false });
              }}
            >
              <ProFormText.Password
                name="newPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="请输入新密码..."
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <ProFormText.Password
                name="okNewPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="请确认新密码..."
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </ProForm>
          </Card>
        </div>
      </Modal>
    </>
  );
};

export default Welcome;
